
module pulse_width_detect(
	input       clk,
	input       rst_n,

	input	    en,     //pin22
	input	    sclk,   //pin3
	input	    sdi,    //pin2
	
	output reg [15:0]   pulse_width
);

localparam HEAD = 16'hA501;

reg [ 2:0]  sck_buf;
reg [31:0]  sdi_buf;
reg [15:0]  pulse_width_buf;


wire        sck_pos;
wire        sck_neg;

assign sck_pos = (sck_buf[2:1] == 2'b01); //posedge
assign sck_neg = (sck_buf[2:1] == 2'b10); //negedge

always @(posedge clk or negedge rst_n)begin
	if(!rst_n)
		sck_buf <= 3'd0;
	else if(en)
		sck_buf <= {sck_buf[1:0],sclk};
    else
        sck_buf <= sck_buf;
end
	
always @(posedge clk or negedge rst_n)begin
	if(!rst_n)
		sdi_buf <= 32'd0;
	else if(en == 1'b0)
		sdi_buf <= 32'd0;
	else if(sck_pos)
		sdi_buf <= {sdi_buf[30:0],sdi};
    else
        sdi_buf <= sdi_buf;
end

always @(posedge clk or negedge rst_n)begin
	if(!rst_n)
		pulse_width <= 16'd50;
	else if(sck_neg && sdi_buf[31:16] == HEAD)
		pulse_width <= sdi_buf[15:0];
    else 
        pulse_width <= pulse_width;
end

endmodule
